using System;
using System.Configuration;
using System.Diagnostics;
using System.Data;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Xml;
using System.Collections;
using System.Runtime.Remoting;
using System.IO;
using System.Windows.Forms;

namespace DeleteFiles
{
	/// <summary>
	/// Summary description for Delete.
	/// </summary>
	public class Delete : System.Windows.Forms.Form
	{
		private System.Diagnostics.EventLog eventLog;
		private System.ComponentModel.Container components = null;

		private void RunDeleteFiles(object sender, EventArgs e)
		{
			XmlDocument doc = new XmlDocument();
			doc.Load(String.Format("{0}.config", Assembly.GetExecutingAssembly().Location));

			IDictionary appSettings = (IDictionary)(new DictionarySectionHandler()).Create(null, null, doc.GetElementsByTagName("appSettings")[0]);

			int daysToStore = Convert.ToInt32(appSettings["daysToStore"]);

			string[] directoriesToDeleteFrom = Regex.Replace((string)appSettings["directoriesToDeleteFrom"], @"\s", "").Split(',');

			try
			{				
				foreach (string directory in directoriesToDeleteFrom)
				{
					DirectoryInfo dir = new DirectoryInfo((string) directory);
					string[] extensionsToDelete = Regex.Replace((string)appSettings["extensionsToDelete"], @"\s", "").Split(',');
					foreach (string type in extensionsToDelete)
					{
						FileInfo[] Document = dir.GetFiles(type);

						DateTime todayDate = DateTime.Now.Date.AddDays(-daysToStore);
				
						foreach( FileInfo f in Document)
						{
							if (f.LastWriteTime.CompareTo(todayDate) == -1)
							{
								if( IsFileReady( f.FullName ))
									f.Delete();
							}					
						}
					}
				}
				Application.Exit();
			}
			catch (Exception d)
			{
				eventLog.WriteEntry(d.InnerException.Message, EventLogEntryType.Error);
			}
		}


		internal static bool IsFileReady(string fileName)
		{
			bool ready = false;
			try
			{
				using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
				{
					ready = true;
				}
			}
			catch
			{
			}
			return ready;
		}

		public Delete()
		{			
			InitializeComponent();
		}

		#region Entry Point
		[STAThread]
		static void Main() 
		{
			try
			{
				Application.Run(new Delete());			
			}
			catch (Exception e)
			{
				MessageBox.Show(e.StackTrace, e.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		#endregion
		
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{			
			// 
			// Delete
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(115, 0);
			this.Enabled = false;
			this.Name = "Delete";
			this.Text = "Delete";
			this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
			this.Load +=new EventHandler(RunDeleteFiles);

		}
		#endregion		
	}
}
